﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace WorkStation.Frameworks.Core.Data.DataTableValidate.Rules
{
    /// <summary>
    /// * 验证单元格数据类型是否符合
    /// </summary>
    /// <typeparam name="TDataType">单元格数据类型</typeparam>
    public class DataTypeRule<TDataType> : RowRuleBase
    {
        public List<string> Columns { get; set; }

        public DataTypeRule(List<string> columns) 
        {
            this.Columns = columns;
        }

        public override ValidateResult Execute(DataRow row, int line)
        {
            ValidateResult res = new ValidateResult() { IsSuccess = true };

            if (this.Columns != null) 
            {
                foreach (string column in this.Columns) 
                {
                    try
                    {
                        var temp = Convert.ChangeType(row[column], typeof(TDataType));
                    }
                    catch (Exception ce) 
                    {
                        res.IsSuccess = false;
                        res.Msg = string.Format("第{0}行的【{1}】列的数据必须为{2}型", line, column, typeof(TDataType).Name);
                    }
                }
            }

            return res;
        }
    }
}
